#include <shell/var.h>
#include <klibc/ctype.h>
#include <klibc/malloc.h>
#include <klibc/string.h>

/*
 * Aggiunge una variabile
 */
int var_add(char *name, char *data)
{
	if(var_ifexist(name)) return -1;	
	else
	{
		shell_var_t *sv = shell_vars;
		
		shell_var_t *temp = (shell_var_t *) malloc(sizeof(shell_var_t));
		strcpy(temp->name, name);
		strcpy(temp->data, data);
		temp->next = sv;
		sv = temp;
		
		return 0;
	}
}


/*
 * Controlla se esiste una variabile
 */
int var_ifexist(char *name)
{
	shell_var_t *sv = shell_vars;
	
	while(sv != NULL)
	{
		if(strcmp(sv->name, name) == 0) return 1;
		sv = sv->next;
	}
	return 0;
}


/*
 * Elimina una variabile
 */
int var_del(char *name)
{
	shell_var_t *sv = shell_vars;
	shell_var_t *t = shell_vars;
	
	if(!var_ifexist(name)) return -1;
	
	while(sv != NULL)
	{
		if(strcmp(sv->name, name) == 0)
		{
			t->next = sv->next;
			free(sv);
			return 0;
		}
		
		t = sv;
		sv = sv->next;
	}
}


/*
 * Ottiene una variabile
 */
char *var_get(char *name)
{
	shell_var_t *sv = shell_vars;
	
	while(sv != NULL)
	{
		if(strcmp(sv->name, name) == 0) return sv->data;
		sv = sv->next;
	}
	return NULL;	
	
}



/*
 * Imposta un valore ad una variabile
 */
int var_set(char *name, char *data)
{
	shell_var_t *sv = shell_vars;
	
	while(sv != NULL)
	{
		if(strcmp(sv->name, name) == 0)
		{
			strcpy(sv->data, data);
			return 0;
		}
		sv = sv->next;
	}
	return -1;	
}
